package test.cluster.net.listener;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;

import test.client.executor.Client;
import test.cluster.MessagePacket;
import test.cluster.ResultPacket;
import test.cluster.MessagePacket.Type;
import test.configuration.ConfigFactory;

public class ListenerSessionHandler extends IoHandlerAdapter {
	private Log log = LogFactory.getLog(this.getClass());
	
	@Override
	public void exceptionCaught(IoSession session, Throwable cause)
			throws Exception {
		cause.printStackTrace();
		session.close(true);
	}

	@Override
	public void sessionOpened(IoSession session) throws Exception {
		log.info("session opened. from: " + session.getRemoteAddress());
	}

	@Override
	public void messageReceived(IoSession session, Object message)
			throws Exception {
		if (message == null) return;
		
		if (message instanceof String) {
			log.info("String message: " + message);
		}
		else if (message instanceof MessagePacket) {
			// Test
			MessagePacket packet = (MessagePacket) message;
			log.info("Configuration type: " + packet.getTestClass() + ", " + packet.getMetaThread().getSleepMode() + ", " + packet.getMessage().toString());
			return;
		}
		
		String body = message.toString();
		if (body.trim().equals(Type.start.toString())) {
			log.info("starting test...");
			
			String testClass = ConfigFactory.getConfiguration().getTestClass();
			Client client = (Client) Class.forName(testClass).newInstance();
			client.execute();
			
			// return the result
			ResultPacket result = new ResultPacket();
			result.setResult(client.getAnalyzer().getResult());
			session.write(result);
		}
		else if (body.trim().equals(Type.getresult.toString())) {
			log.info("sending result...");
		}
		else if (body.trim().equals(Type.quit.toString())) {
			log.info("quit...");
			session.close(true);
			return;
		}
		else {
			log.error("Unexpected message: " + body);
		}
	}
}
